package com.gillion.grule.client.components;

import com.gillion.grule.client.core.Component;
import com.gillion.grule.client.core.Context;
import com.gillion.grule.client.core.ExecuteComponent;
import com.gillion.grule.client.utils.ContextHolder;
import com.google.common.collect.Lists;
import java.lang.reflect.Method;
import java.util.List;
import org.mvel2.MVEL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




@Component("LocalService")
public class LocalServiceComponent extends ExecuteComponent
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LocalServiceComponent.class);


    public <T> T execute(String express, Context context) {
        String[] args = express.split("##");
        Object object = ContextHolder.getBean(args[0]);
        List<Object> parms = Lists.newArrayList();
        Class<?> clazz = object.getClass();
        Object result = null;
        try {
            List<Class<?>> list = Lists.newArrayList();
            for (int i = 2; i < args.length; i++) {
                String parm = args[i];
                if (parm.startsWith("@") && parm.endsWith("@")) {
                    parm = parm.replace("@", "");
                    Object mvelObj = MVEL.eval(parm, context);
                    list.add(mvelObj.getClass());
                    parms.add(mvelObj);
                } else {
                    list.add(args[i].getClass());
                    parms.add(args[i]);
                }
            }
            Method m1 = clazz.getDeclaredMethod(args[1], list.toArray(new Class[args.length - 2]));

            result = m1.invoke(clazz.newInstance(), parms.toArray(new Object[args.length - 2]));
        } catch (Exception e) {
            LOGGER.error("组件异常", e);
        }

        return (T)result;
    }
}

